// pages/shopping-mall/shopping-mall.js
var app = getApp();
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');

var loadingMore = false;
var dataall;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    uid: '',
    token: '',
    userinfo: '',
    catadata: '',
    currcata: 0,
    selectCata: {},

    infodata: [],
    goodsList: [],

    content_w: 320,

    noData: false,

    canEdit: false,

    colorSet: '',

    wz_item_img_w_1: 0,
    wz_item_img_w_2: 0,
    wz_item_img_w_3: 0,
    wz_item_img_h_1: 0,
    wz_item_img_h_2: 0,
    wz_item_img_h_3: 0,

    UIType: 1, //UI标记，可根据这个值渲染不同的UI
    showNav: true,  //是否显示底部导航，默认显示

    swiper_height: 397
  },

  albumId: '',//初始选中的分类 由参数options传入
  albumMuster: '', //指定分类分类集合，由参数options传入，可以选中某些分类数据进行渲染

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    })

    var titlename = options.title ? options.title : '资讯';
    wx.setNavigationBarTitle({
      title: titlename,
    });

    var that = this;
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('zixun/zixun', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    this.albumId = options.albumid ? options.albumid : '';//初始选中的分类
    this.albumMuster = options.albums ? options.albums : '';//指定分类分类集合，由参数options传入，可以选中某些分类数据进行渲染
    var UItype = options.uitype ? options.uitype : '1';
    var show_nav = options.shownav == "false" ? false : true;
    wx.getSystemInfo({
      success: function (res) {
        var wid_1 = res.windowWidth - 25;
        var wid_2 = (res.windowWidth - 35) / 2;
        var wid_3 = (res.windowWidth - 45) / 3;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        var swiperHeight = show_nav ? (res.windowHeight - 83) : (res.windowHeight - 33);
        swiperHeight = isIphone_x ? (swiperHeight - 20) : swiperHeight;
        that.setData({
          isIphone_x: isIphone_x,
          UIType: UItype,
          showNav: show_nav,
          content_w: res.windowWidth,
          swiper_height: swiperHeight,
          wz_item_img_w_1: wid_1,
          wz_item_img_w_2: wid_2,
          wz_item_img_w_3: wid_3,
          wz_item_img_h_1: wid_1 / 2,
          wz_item_img_h_2: wid_2,
          wz_item_img_h_3: wid_3
        });
      }
    });

    that.loadClasslyData();
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token
        });
        that.getUserInfo(res.uid);
        // that.getEditAuth();
      }
    }, '');
  },

  getUserInfo: function (uid) {
    var that = this;
    util.api({
      data: {
        "uid": uid,
        "publickey": util.publiccode,
        "ac": "userinfo"
      },
      success: function (responseData) {
        that.setData({
          userinfo: responseData.data
        });
      }
    });
  },

  //获取企业成就 数据子分类
  loadClasslyData: function () {
    var that = this;
    var params = '';
    var actionItem = '';
    params = {
      ac: "getalbum",
      publickey: util.publiccode,
      uid: util.orgid,
      type: 8
    }
    
    console.log("getalbum params: ", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("企业动态类别：", result);
        if (!result.msg) {
          var albumMusterArray = [];
          //如果由指定分类集合，则筛选
          if (that.albumMuster && that.albumMuster.length >= 1){
            for (var i = 0; i < result.length; i++) {
              if (that.albumMuster.indexOf(result[i].id) >= 0) {
                albumMusterArray = albumMusterArray.concat(result[i]);
              }
            }
            dataall = albumMusterArray;  
          } else {
            dataall = result;
          }
          var curAlbum = dataall[0];
          var cataindex = 0;
          if (that.albumId){
            for(var i = 0; i < dataall.length; i++){
              if(dataall[i].id == that.albumId){
                curAlbum = dataall[i];
                cataindex = i;
                break;
              }
            }
          }
          that.setData({
            catadata: dataall,
            selectCata: curAlbum,
            currcata: cataindex
          });
        }
        that.loadGoodsListData(1);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      var col = color.shop_col ? parseInt(color.shop_col) : 2;
      col = col > 0 ? col : 2;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 6.5) / col
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function () {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //swiper滑动结束
  swiperMoveFinish: function(e){
    var current = e.detail.current;
    console.log("current = " + current);
    this.changeCata(current);
  },
  touchTabAction: function(event){
    var cataindex = event.currentTarget.dataset.index;
    this.changeCata(cataindex);
  },
  changeCata: function (cataindex) {
    
    var that = this;
    
    // wx.setNavigationBarTitle({
    //   title: dataall[cataindex].name
    // })

    that.setData({
      selectCata: that.data.catadata[cataindex],
      currcata: cataindex,
    });

    var data = that.data.selectCata.datalist;
    console.log("select data = " + data);

    if (!data || data.length <= 0) {
      that.loadGoodsListData(1);
    }
  },

  loadMore: function () {
    var albumid = this.data.selectCata.id;
    var hasMore = this.data.selectCata.hasMore;
    if (!loadingMore && hasMore) {
      var page = this.data.selectCata.page + 1;
      this.loadGoodsListData(page);
    }
  },

  loadGoodsListData: function (cpage) {
    loadingMore = true;
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    });
    var that = this;
    var albumid = that.data.selectCata.id;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '8',
      albumid: albumid,
      orgid: util.orgid,
      toporder: '1',
      page: cpage.toString(),
      num: 10
    };

    console.log("企业动态请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("企业动态数据:", responseData);
        var resData = responseData.data;
        var newData = '';
        var cataData = that.data.catadata;
        var oldDatas = '';
        var selIndex = 0;
        for(var i = 0; i < cataData.length; i++){
          if (albumid == cataData[i].id){
            oldDatas = cataData[i];
            selIndex = i;
            break;
          }
        }
        if (resData.msg) {
          oldDatas.hasMore = false;
          if (cpage <= 1) {
            oldDatas.noData = true;
          };
        } else {
          if (cpage > 1) {
            newData = oldDatas.datalist.concat(resData);
          } else {
            newData = resData;
          };
          oldDatas.datalist = newData;
        }
        oldDatas.page = cpage;
        cataData[selIndex] = oldDatas;
        that.setData({
          catadata: cataData
        });
        console.log("cataData:", cataData);
        wx.hideLoading();
        loadingMore = false;
      }
    });
  },
  

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.redirectTo({ url: url });
    }
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.navigateTo({ url: url });
    }
  },

  releaseAction: function(){
    var selAlbum = this.data.selectCata;
    var params = "albumid=" + selAlbum.id + "&albumname=" + selAlbum.name;
    var path = "/pages/release-jj/release-jj?" + params;
    wx.navigateTo({
      url: path,
    })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        wx.navigateTo({
          url: navPath,
        })
      } else {
        wx.redirectTo({ url: path });
      }
    }
  },
})